import { Component, input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-my-paginator',
  imports: [FormsModule],
  templateUrl: './my-paginator.component.html',
  styleUrl: './my-paginator.component.css',
})
export class MyPaginatorComponent {
  //表格的总记录数
  totalRecordsCount = input<number>(0);
  //每页显示个数的选项
  pageSizeOptions = input.required<number[]>();
  //用户选择每页显示个数选项的索引
  currentPageSizeOptionsIndex = signal<number>(0);
  //当前页码索引
  currentPageIndex = signal<number>(0);
  //每页显示的记录数
  get currentPageSize(): number {
    return this.pageSizeOptions()[this.currentPageSizeOptionsIndex()];
  };

  //最大页码
  get maxPageNumber(): number {
    return Math.ceil(this.totalRecordsCount() / this.currentPageSize);
  };

  //当前页码
  get currentPageNumber() {
    return this.currentPageIndex() + 1;
  }
  set currentPageNumber(value: number) {
    if (value < 1) {
      this.currentPageIndex.update((preview) => 0);
    } else if (value > this.maxPageNumber) {
      this.currentPageIndex.update((preview) => this.maxPageNumber - 1);
    } else {
      this.currentPageIndex.update((preview) => value - 1);
    }
  }

  //当用户重新选择页面能显示的记录数时，若当前页码超出最大页码，强制切换到最大页码
  onPageSizeOptionChange(newPageSize: number) {
    if (this.currentPageIndex() > this.maxPageNumber - 1) {
      this.currentPageIndex.set(this.maxPageNumber - 1);
    } else {
      this.currentPageSizeOptionsIndex.set(newPageSize);
    }
  }
}
